#   Copyright (C) 2008      Tri Tech Information Systems Inc.
# 
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
# 
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
# 
#   You should have received a copy of the GNU General Public License along
#   with this program; if not, write to the Free Software Foundation, Inc.,
#   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#   

class GeneratorAdaptor( object ):
    '''Adapt Wrapper objects to use __getitem__ for string formatting
    '''
    def __init__( self, wrapper ):
        self.wrapper = wrapper

    def __getitem__( self, item ):
        head = self.wrapper
        for i in item.split('.'):
            try:
                fn = getattr( head, 'generate_'+i )
            except AttributeError:
                head = getattr( head, i )
            else:                
                head = fn()

        # How the (*&!$ do you tell a list from a string without relying on
        #  the actual type, which is really un-pythonic and totally broken
        #  by things like QStringList
        if type(head) is list:
            head = '\n'.join( head )

        return head

def generator( f ):
    '''Format output as per Wrapper.generate()
    '''
    def m( self, *a, **kw ):
        return f( self, *a, **kw ) % GeneratorAdaptor( self )

    return m

def argument_list( lst ):
    return ', '.join( i for i in lst if i )

def formatter( fmt ):
    def gen( f ):
        def m( *a, **kw ):
            return fmt( f(*a, **kw) )
        return m
    return gen

def indent( txt, nspaces = 4 ):
    '''Inefficient method that accepts strings or lists and indents each line
    '''
    if type(txt) is list:
        l = []
        for s in txt:
            l.extend( s.split('\n') )
        txt = l
    else:
        txt = txt.split('\n')

    return '\n'.join([ (' '*nspaces)+s for s in txt ])

